<template>
  <div class="yy-page yy-base-employee">
    <div class="yy-page-search" v-if="showSearch">
      <WidgetForm ref="searchFormWidget" :option="{
        style: 'display: flex;',
        itemStyle: 'margin-right: 10px;margin-bottom: 0;align-items: center;'
      }" :form-fields="search.formFields" :form-buttons="search.formButtons" />
    </div>
    <div class="yy-page-header">
      <div class="yy-page-header_title">
        <el-button  plain icon="Plus" type="primary" @click="onOpenDialog()">新增</el-button>
      </div>
      <div class="yy-page-header_action">
        <right-toolbar @showSearch="onShowSearch" @queryTable="getList"></right-toolbar>
      </div>
    </div>
    <div class="yy-page-data">
      <WidgetTable  ref="tableDataRef" :is-loading="table.isLoading" :columns="table.columns" :data="table.data" :formats="table.formats" :paging-data="table.paging"></WidgetTable>
    </div>

    <WidgetFormDialog ref="widgetFormDialogRef"
                      :form-fields="dialog.formFields"
                      :model-instance="dialog.modelInstance"
                      :save-api-fun="dialog.saveApiFun"
                      :update-api-fun="dialog.updateApiFun"
                      :option="{
                        dialogWidth: '600px',
                        businessName: '优先级',
                    }"
                      @edit-callback="onEditCallback"
    />
  </div>
</template>

<script setup lang="ts">

import {onBeforeMount, reactive, ref} from "vue";
import {TableColumn, WidgetFormField} from "@/model/Definition";
import {BaseModel} from "@/model/BaseModel";
import {formatDate} from "@/utils/yayi";
import WidgetTable from "@/components/widget/WidgetTable.vue";
import WidgetFormDialog from "@/components/widget/WidgetFormDialog.vue";
import WidgetForm from "@/components/widget/WidgetForm.vue";
import {PriorityModel} from "@/model/PriorityModel";
import PriorityApi from "@/api/queue/PriorityApi";
import {getDicts} from "@/api/system/dict/data"

const showSearch = ref(true)
const dialog = reactive<{formFields: WidgetFormField[],modelInstance: BaseModel, saveApiFun: any, updateApiFun: any}>({
  modelInstance: new PriorityModel(),
  saveApiFun: savePriority,
  updateApiFun: updatePriority,
  formFields: [
    {field: 'priorityType', label: '队列类型', type: 'select', options: [],
      placeholder: '请选择队列', required: [{required: true, message: '队列不能为空', trigger: 'change'},],
      atChange: (val) => {
        const priorityTypeField = dialog.formFields.find(item => item.field === 'priorityType')
        const select = priorityTypeField.options.find(item => item.value == val)

        const prefixField = dialog.formFields.find(item => item.field === 'prefix')
        prefixField.initVal = select.label.substring(0, 1);
        widgetFormDialogRef.value.setFieldValue('prefix', prefixField.initVal)
      }
    },
    {field: 'prefix', label: '前缀', type: 'text', initVal: null, placeholder: '请输入队列显示前缀'},
    {field: 'sortNo', label: '优先级', type: 'number', initVal: 1, config: {}, placeholder: '请输入优先级'},
    {field: 'sortRule', initVal: '1', label: '排序规则', type: 'select', options: [],
      placeholder: '请选择排序规则',
      required: [{required: true, message: '规则不能为空', trigger: 'change'}],
      atChange: (val) => {
        const intervalFormField = dialog.formFields.find(item => item.field === 'sortInterval')
        intervalFormField.hide = val != '3'
      }
    },
    {field: 'sortInterval', initVal: 2, hide: true, label: '间隔人数', type: 'number', placeholder: '请输入间隔人数' },
    {field: 'state', label: '状态', type: 'radioGroup', initVal: 1, options: [{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ]
})

const search = reactive<{formFields: WidgetFormField[],formData: any, formButtons: any, modelInstance: BaseModel, searchApiFun:any}>({
  modelInstance: new PriorityModel(),
  searchApiFun: PriorityApi.list,
  formData: {},
  formFields: [
    {field: 'searchKey', config: {input: {clearable: true}}, placeholder:"请输入名称或编码的关键字", label: '关键字', type: 'text', style:'width: 200px;',},
    {field: 'state', config:{select: {clearable: true}}, label: '状态', type: 'select', initVal: -1, style:'width: 100px;', options: [{label: '全部', value: -1},{label: '启用', value: 1}, {label: '停用', value: 0}]}
  ],
  formButtons: [
    {type: 'primary', label:'搜索', icon: 'search', atClick: ()=> {
        const formData = searchFormWidget.value.getFormFieldValue()
        search.formData = Object.assign({}, formData, {searchKey: formData.searchKey?.length ? formData.searchKey : null, state: formData.state === -1 ? null : formData.state})
        getList(1)
      }
    },
    {type: 'default', label: '清空', icon: 'refresh', atClick: () => {
        searchFormWidget.value.resetFields()
      }
    }
  ]
})

const table = reactive<{
  isLoading: boolean,
  paging: any,
  columns: TableColumn[],
  data: PriorityModel[],
  formats?: any
}>({
  isLoading: false,
  columns: [
    {
      "field":"index",
      "label":"序号",
      "type": "index",
      "showable":true,
      "align": 'center',
      "width": 60,
      "fixed": 'left'
    },
    {
      "field":"name",
      "label":"名称",
      "showable":true,
      "fixed": 'left'
    },
    {
      "field":"prefix",
      "label":"前缀",
      "showable":true
    },
    {
      "field":"code",
      "label":"值",
      "showable":true
    },
    {
      "field":"sortNo",
      "label":"排序号",
      "showable":true,
      "sortable": true
    },
    {
      "field":"updateBy",
      "label":"更新用户",
      "showable":true,
      "width": 120
    },
    {
      "field":"updateTime",
      "label":"更新时间",
      "showable":true,
      "width": 140
    },
    {
      "field":"state",
      "label":"状态",
      "showable":true,
      "sortable":false,
      "align": 'center',
      "width": 60,
      "fixed": 'right'
    },
    {
      "field":"action",
      "label":"操作",
      "width": 150,
      "showable":true,
      "sortable":false,
      "align": 'center',
      "fixed": 'right'
    }
  ],
  paging: {
    isPaging: false
  },
  data: [],
  formats: {
    'state': {
      textType:'text',
      typeFormat: PriorityModel.getStateType,
      labelFormat: PriorityModel.getStateLabel
    },
    'updateTime': {
      labelFormat:  (val) =>formatDate(val)
    },
    'action': {
      items: [
        {label: '编辑',elType: 'button', value: 'edit', atClick: (data) => onOpenDialog(data)},
        {label: '删除',elType: 'button', value: 'delete',  confirm: {title: '您确定要删除该员工吗？', atConfirm: (data) => onDelete(data)}}
      ]
    }
  }
})

const queueSortRule = ref([
  {label: '候诊前', value: '1'},
  {label: '候诊后', value: '2'},
  {label: '间隔插入', value: '3'},
])

const searchFormWidget = ref()
const widgetFormDialogRef = ref()
const tableDataRef = ref()

onBeforeMount(() => {
  getList()
  getDictDataByType()
  const sortRuleFormField = dialog.formFields.find(item => item.field === 'sortRule')
  sortRuleFormField.options = queueSortRule.value
})

const onShowSearch = () => {
  showSearch.value = !showSearch.value
  tableDataRef.value.onWindowResize()
}

const getDictDataByType = () => {
  const dictType = "queue_priority_flag"
  getDicts(dictType).then((res) => {
    if (res.code === 200) {
      const formField = dialog.formFields.find(item => item.field === 'priorityType')
      formField.options = res.data.map(item => Object.assign({
        label: item.dictLabel,
        value: item.dictValue
      }))
    }
  })
}

const getList = () => {
  table.isLoading = true
  PriorityApi.list().then((res) => {
    table.data = res
    table.isLoading = false
  }, () => {
    table.isLoading = false
  })
}

const onOpenDialog = (data?: PriorityModel) => {
  let params = null
  if (data) {
    const config = JSON.parse(data.config)
    params = {
      id: data.id,
      priorityType: data.code,
      prefix: data.prefix,
      sortNo: data.sortNo,
      sortRule: config.sortRule.rule,
      sortInterval: config.sortRule.interval || 2, // 默认2
      state: data.state
    }
    const sortIntervalFormField = dialog.formFields.find(item => item.field === 'sortInterval')
    sortIntervalFormField.hide = config.sortRule.rule != 3
  }
  widgetFormDialogRef.value.onShowDialog(new PriorityModel().deserialize(params))
}

const onDelete = (data) => {
  PriorityApi.delete(data.id).then(() => {
    const index = table.data.findIndex(item => item.id === data.id);
    if (index >= 0) {
      table.paging = Object.assign({}, table.paging, {
        total: table.paging.total - 1
      })
      table.data.splice(index, 1)
    }
  })
}

const onEditCallback = (data: PriorityModel) => {
  const index = table.data.findIndex(item => item.id === data.id);
  if (index < 0) {
    table.data.unshift(data)
    table.paging = Object.assign({}, table.paging, {
      total: table.paging.total + 1
    })
  } else {
    table.data.splice(index, 1, data)
  }
}

function updatePriority (id, data) {
  return new Promise((resolve, reject) => {
    const priorityOptions =  dialog.formFields.find(item => item.field === 'priorityType').options
    const priority = priorityOptions.find(item => item.value === data.priorityType)
    data.name = priority.label
    data.code = priority.value
    PriorityApi.update(id, new PriorityModel().deserialize(Object.assign({}, data, {
      id: id,
      config: JSON.stringify({sortRule: {rule: data.sortRule, interval: data.sortRule === '3' ? data.sortInterval: null}})
    }))).then((res) => {
      resolve(res)
    }, (err) => reject(err))
  })
}
function savePriority (data) {
  return new Promise((resolve, reject) => {
    const priorityOptions =  dialog.formFields.find(item => item.field === 'priorityType').options
    const priority = priorityOptions.find(item => item.value === data.priorityType)
    data.name = priority.label
    data.code = priority.value
    PriorityApi.save(new PriorityModel().deserialize(Object.assign({}, data, {
      config: JSON.stringify({sortRule: {rule: data.sortRule, interval: data.sortRule === '3' ? data.sortInterval : null}})
    }))).then((res) => {
      resolve(res)
    }, (err) => reject(err))
  })
}
</script>
<style scoped lang="scss">
.yy-base-employee {
  height: 100%;
}
</style>